package com.base.servlet.message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Jeffrey
 * @date: 2022/01/22/22:46
 * @description: Http 协议解析类, 行，头，体
 */
@ChannelHandler.Sharable
public class HttpMessageCodecSharable extends MessageToMessageCodec<ByteBuf,HttpMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, HttpMessage msg, List<Object> out) throws Exception {

        /*这里需要自己创建ByteBuf*/
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes(msg.getLine().getBytes(StandardCharsets.UTF_8));
        buffer.writeBytes(msg.getSeparator());
        Map<String,String> map = msg.getHeader();
        for (String name: map.keySet()){
            buffer.writeBytes(name.getBytes(StandardCharsets.UTF_8));
            /*0x3A = :*/
            buffer.writeByte(0x3A);
            buffer.writeBytes(map.get(name).getBytes(StandardCharsets.UTF_8));
            buffer.writeBytes(msg.getSeparator());
        }
        /*分隔符*/
        buffer.writeBytes(msg.getSeparator());
        buffer.writeBytes(msg.getBody().getBytes(StandardCharsets.UTF_8));
        out.add(buffer);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        String s = msg.toString(CharsetUtil.UTF_8);
        HttpMessage message = new HttpMessage();
        Map<String,String> map = new HashMap<>();

        String[] split = s.split("\r\n");
        message.setLine(split[0]);
        int i = 1;
        while (i < split.length-1 && !split[i].equals("") ){
            String[] strings = split[i].split(":");
            if (strings[0].toLowerCase().equals("host")){
                strings[1] = strings[1] + ":" +strings[2];
            }
            map.put(strings[0],strings[1]);
            i++;
        }
        message.setHeader(map);
        message.setBody(split[split.length-1]);
        /*请求体字节流*/
        message.setBytes(message.getBody().getBytes(StandardCharsets.UTF_8));
        out.add(message);
    }
}
